//
//  AddFeedViewController.m
//  iRSSNews
//
//  Created by bk_sport on 12/29/12.
//  Copyright (c) 2012 bk_sport. All rights reserved.
//

#import "AddFeedViewController.h"
#import "FeedsViewController.h"
#import "AppDelegate.h"
#import "Feed.h"

@interface AddFeedViewController ()
{
    int rowEditName;
    Feed *feed;
}

@end

@implementation AddFeedViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSError *error;
	if (![[self fetchedCategories] performFetch:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);
	}
    if (![[self fetchedFeeds] performFetch:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);
	}
    feed = [self.fetchedFeeds.fetchedObjects objectAtIndex:self.selectedRowFeed];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(buttonDoneClick:)];
    
    if (_isAdd == YES)
    {
        self.title = NSLocalizedString(@"AddFeedKey", @"");
        self.feedNameLB.text = NSLocalizedString(@"FeedNameKey", @"");
    }
    else
    {
        self.title = NSLocalizedString(@"EditFeedKey", @"");
        self.feedNameLB.text = NSLocalizedString(@"NewFeedNameKey", @"");
        self.feedNameTF.text = feed.name;
        self.feedRSSLB.hidden = YES;
        self.feedRSSTF.hidden = YES;
    }

    self.feedRSSTF.delegate = self;
    self.feedNameTF.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void) buttonDoneClick:(id) sender
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    
    NSString *stringFeedName = self.feedNameTF.text;
    NSString *trimedStringFeedName = [stringFeedName stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceCharacterSet]];
    NSString *stringFeedRSS = self.feedRSSTF.text;
    NSString *trimedStringFeedRSS = [stringFeedRSS stringByTrimmingCharactersInSet:
                                      [NSCharacterSet whitespaceCharacterSet]];
    if (_isAdd == YES) {
        if(trimedStringFeedName.length != 0)
            if(trimedStringFeedRSS.length != 0)
            {
                NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
                NSInteger numberOfFeeds = [standardUserDefaults integerForKey:@"numberOfFeeds"];
                
                Feed *item = [NSEntityDescription
                                  insertNewObjectForEntityForName:@"Feed"
                                  inManagedObjectContext:context];
                item.id = [NSNumber numberWithInt:numberOfFeeds];
                NSLog(@"%i", numberOfFeeds);
                item.name = self.feedNameTF.text;
                item.link = self.feedRSSTF.text;
                //Du lieu gia cho numberOfNews
                item.numberOfNewNews=[NSNumber numberWithInt:5];
                item.category = self.categoryItem;
                
                NSError *error;
                if (![context save:&error]) {
                    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
                }
                
                numberOfFeeds++;
                [standardUserDefaults setInteger:numberOfFeeds forKey:@"numberOfFeeds"];
                [standardUserDefaults synchronize];

                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertAddFeedOKKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
                [alert show];
                [self.navigationController popViewControllerAnimated:YES];
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertAddFeedRSSFailedKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
                [alert show];
                [self.feedRSSTF becomeFirstResponder];
            }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertAddFeedNameFailedKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
            [alert show];
            [self.feedNameTF becomeFirstResponder];
        }
    }
    else
    {
        if(trimedStringFeedName.length != 0)
        {
                feed.name = self.feedNameTF.text;
            
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertEditFeedOKKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
                [alert show];
                
                NSError *error;
                if (![context save:&error]) {
                    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
                }
                
                [self.navigationController popViewControllerAnimated:YES];
        }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertAddFeedNameFailedKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
                [alert show];
                [self.feedNameTF becomeFirstResponder];
            }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.feedNameTF resignFirstResponder];
    [self.feedRSSTF resignFirstResponder];
    
    return YES;
}

#pragma mark - fetchCategories

- (NSFetchedResultsController *)fetchedCategories
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    if (_fetchedCategories != nil) {
        return _fetchedCategories;
    }
    static NSString *EntityName = @"Category";
    static NSString *CacheName = @"Category";
    [NSFetchedResultsController deleteCacheWithName:@"Category"];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:EntityName inManagedObjectContext:appDelegate.managedObjectContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
    fetchRequest.entity = entity;
    fetchRequest.sortDescriptors = @[sort];
    fetchRequest.fetchBatchSize = 20;
    
    
    _fetchedCategories = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:CacheName];
    
    _fetchedCategories.delegate = self;
    return _fetchedCategories;
}

#pragma mark - fetchedFeed

- (NSFetchedResultsController *)fetchedFeeds
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    if (_fetchedFeeds != nil) {
        return _fetchedFeeds;
    }
    static NSString *EntityName = @"Feed";
    static NSString *CacheName = @"Feed";
    [NSFetchedResultsController deleteCacheWithName:@"Feed"];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:EntityName inManagedObjectContext:appDelegate.managedObjectContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
    fetchRequest.entity = entity;
    fetchRequest.sortDescriptors = @[sort];
    fetchRequest.fetchBatchSize = 20;
    
    
    _fetchedFeeds = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:CacheName];
    _fetchedFeeds.delegate = self;
    
    return _fetchedFeeds;
}

@end
